<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <!-- 引入 Bootstrap 样式 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
            <div class="card mt-5">
                <div class="card-body">
                    <h3 class="card-title text-center">用户登录</h3>
                    <?php
                    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                        $host = 'localhost';
                        $dbname = 'test';
                        $user = 'root';
                        $password = 'root';

                        try {
                            $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
                            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                            $username = $_POST['username'];
                            $userpassword = $_POST['password'];

                            $sql = "SELECT * FROM user WHERE name = :name AND password = :password";
                            $stmt = $pdo->prepare($sql);
                            $stmt->execute(['name' => $username, 'password' => $userpassword]);
                            $user = $stmt->fetch(PDO::FETCH_ASSOC);

                            if ($user) {
                                header("Location: users.php");
                                exit;
                            } else {
                                echo "<div class='alert alert-danger' role='alert'>用户名或密码错误</div>";
                            }
                        } catch (PDOException $e) {
                            echo "<div class='alert alert-danger' role='alert'>数据库连接失败: " . $e->getMessage() . "</div>";
                        }
                    }
                    ?>
                    <form method="POST" action="login.php">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">登录</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 引入 Bootstrap 脚本 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
